package ch5.CountDownLatchCase;

import util.Debug;

import java.util.concurrent.CountDownLatch;

public abstract class AbstractService implements Service{
    protected boolean started = false;
    protected final CountDownLatch latch;

    public AbstractService(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void start() {
        new ServiceStarter().start();
    }


    @Override
    public boolean isStarted() {
        return started;
    }

    protected abstract void doStart() throws Exception;


    @Override
    public void stop() {}

    class ServiceStarter extends Thread {
        @Override
        public void run() {
           final String serviceName = AbstractService.this.getClass().getSimpleName();
           Debug.info("Starting %s", serviceName);
           try {
               doStart();
               started = true;
           } catch (Exception e) {
               e.printStackTrace();
           } finally {
               latch.countDown();
               Debug.info("Done starting %s", serviceName);
           }
        }
    }
}
